<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class SwitchElectric extends Model
{
    protected $table = 'xfy_switch_electric';
    protected $primaryKey = 'id';

    protected $fillable = ['switch_id', 'quantity', 'created_time'];


    public static function addTodayElectric(){
        $switches = SwitchModel::whereNotNull('machine_code')->where('pid', '!=', 0)->pluck('machine_code', 'id')->toArray();
        if (empty($switches)) {
            return;
        }

        $yesterdayTimestamp = strtotime(date("Y-m-d", strtotime("-1 day")));
        //刚过0点，记录昨天一天的电量
        foreach ($switches as $k => $v) {
            $newest = self::where('switch_id', $k)->where('created_time', $yesterdayTimestamp)->first();
            if (empty($newest)) {
                $data['switch_id'] = $k;
                $data['created_time'] = strtotime(date("Y-m-d", strtotime("-1 day")));

                $beforeYesterdayTimestamp = strtotime(date("Y-m-d", strtotime("-2 day")));
                $beforeYesterday = self::where('switch_id', $k)->where('created_time', $beforeYesterdayTimestamp)->first();
                $jsonData = SwitchData::getLatestRedisData($v);
                if (empty($jsonData)) {
                    break;
                }
                if (empty($beforeYesterday)) {
                    $data['quantity'] = $jsonData['electricQuantity'];
                } else {
                    $data['quantity'] = $jsonData['electricQuantity'] - $beforeYesterday['quantity'];
                }
                DB::table('xfy_switch_electric')->insert($data);
            } else {
                continue;
            }
        }
    }
}